package com.sunqizhong.controller;

import com.sunqizhong.entity.AliyunOSSProperties;
import com.sunqizhong.entity.Result;
import com.sunqizhong.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

/*    private final String bucketName = "java147-tlias-sunqizhong";
    private final String endpoint = "https://oss-cn-wuhan-lr.aliyuncs.com";*/
/*    @Value("${aliyun.oss.bucket}")
    private String bucketName;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;*/

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;


    /*
    * 文件上传---本地存储
    * */
/*    @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile file) throws IOException {
        log.info("参数：{},{},{}",username,age,file);
        //1、获取原始文件名
        String originalFilename = file.getOriginalFilename(); //eg:001.jpg
        originalFilename.substring(originalFilename.lastIndexOf("."));

        //2、通过UUID生成随机字符串
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //2、将前端上传的文件存到本地
        file.transferTo(new File("E:/java学/" + newFileName));
        return Result.success(newFileName);
    }*/

    /*
    * 文件上传-阿里云OSS存储
    * */
    @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile file) throws Exception {
        log.info("参数：{}",file);
        //1、获取原始文件名，截取后缀
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}",originalFilename);
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //2、调用阿里云OSS工具类，将文件上传到OSS
        String url = AliyunOSSUtils.upload(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getBucket(), file.getBytes(), extName);

        //3、返回图片路径
        return Result.success(url);
    }
}
